package com.dhcc.sds.busi.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateTime;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.dhcc.cdc.busi.entity.CdcEpisodeEntity;
import com.dhcc.cdc.busi.service.ICdcEpisodeService;
import com.dhcc.cdc.sys.cache.config.CdcConfigCache;
import com.dhcc.cdc.sys.entity.ConfigurationEntity;
import com.dhcc.cdc.sys.service.IConfigurationService;
import com.dhcc.core.config.properties.SysProperties;
import com.dhcc.core.framework.base.controller.BaseController;
import com.dhcc.core.framework.base.warpper.EmptyWarpper;
import com.dhcc.core.framework.exception.BizException;
import com.dhcc.core.framework.exception.BizExceptionEnum;
import com.dhcc.core.framework.result.R;
import com.dhcc.core.framework.result.page.PageFactory;
import com.dhcc.core.framework.security.ShiroKit;
import com.dhcc.core.framework.util.CommonUtil;
import com.dhcc.core.modules.system.entity.User;
import com.dhcc.sds.base.entity.SdsQcentityRuleEntity;
import com.dhcc.sds.base.service.ISdsCommonService;
import com.dhcc.sds.base.service.ISdsQcentityRuleService;
import com.dhcc.sds.base.service.ISdsQcentityService;
import com.dhcc.sds.busi.entity.SdsQcincaseEntity;
import com.dhcc.sds.busi.entity.SdsQcincaseOperlogEntity;
import com.dhcc.sds.busi.service.ISdsMedicalGroupService;
import com.dhcc.sds.busi.service.ISdsQcFormShowService;
import com.dhcc.sds.busi.service.ISdsQcfitemExecresultService;
import com.dhcc.sds.busi.service.ISdsQcincaseService;
import com.dhcc.sds.standard.dto.CdcEpisodeDto;
import com.dhcc.sds.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;

/**
 * 病历入组
 *
 * @ClassName: SdsQcincaseController
 * @Description: TODO
 * @author zhangdc
 * @date 2021-05-27 10:09:15
 */
@Controller
@RequestMapping("${sys.backendPath}/sds/sdsmedicalgroup")
public class SdsMedicalGroupController extends BaseController {

    private String PREFIX = "/backend/sds/sdsmedicalgroup/";

    @Autowired
    private ISdsQcentityService sdsQcentityService;

    @Autowired
    private ICdcEpisodeService cdcEpisodeService;

    @Autowired
    private ISdsCommonService sdsCommonService;

    @Autowired
    private ISdsMedicalGroupService sdsMedicalGroupService;

    @Autowired
    private ISdsQcentityRuleService sdsQcentityRuleService;
    @Autowired
    private IConfigurationService configurationService;

    @Autowired
    private ISdsQcfitemExecresultService sdsQcfitemExecresultService;
    @Autowired
    private ISdsQcFormShowService sdsQcFormShowService;
    @Autowired
    private SysProperties sysPro;
    @Autowired
    private ISdsQcincaseService sdsQcincaseService;


    /**
     * 跳转到病历入组列表首页
     */
    @RequestMapping("")
    public String index(Model model){
        Date lastDay = DateUtil.getEndDayOfMonth();
        DateTime firstday = DateUtil.getDateByDay(DateTime.of(lastDay), -180);
        //JSONObject list = sdsQcentityService.getQcentity();
        //获取科室信息
        JSONObject deptMap = sdsCommonService.findDeptList();
        JSONObject statusMap = sdsMedicalGroupService.findFormStatus();
        // 单病种医生是否可以直接上报配置
        String formCheckType = CdcConfigCache.me().getValueByKey("SDS", "SDFormCheckType");
        // 是否启用过程质控
        String enableIPQC = CdcConfigCache.me().getValueByKey("SDS", "EnableIPQCModule");
        model.addAttribute("formCheckType", formCheckType);
        model.addAttribute("enableIPQC", enableIPQC);
        model.addAttribute("startDate", firstday);
        model.addAttribute("endDate", lastDay);
        //model.addAttribute("qcentity", list);
        model.addAttribute("deptMap", deptMap);
        model.addAttribute("statusMap", statusMap);
        return PREFIX + "sdsmedicalgroup.html";
    }

    /**
     * 获取病历入组列表
     */
    @SuppressWarnings("unchecked")
    /*@RequestMapping(value = "/list")
    @ResponseBody
    public Object list(@RequestParam Map<String, Object> params){
        Page<CdcEpisodeEntity> page = new PageFactory<CdcEpisodeEntity>().defaultPage();
        List<CdcEpisodeDto> result = this.sdsMedicalGroupService.pageEpisode(page,params);
        Page<CdcEpisodeDto> dtoPage = new PageFactory<CdcEpisodeDto>().defaultPage();
        BeanUtil.copyProperties(page,dtoPage);
        dtoPage.setRecords(result);
        return R.packForBT(dtoPage);
    }*/
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(@RequestParam Map<String, Object> params) {
        Page<CdcEpisodeDto> page = new PageFactory<CdcEpisodeDto>().defaultPage();
        List<CdcEpisodeDto> result = this.sdsMedicalGroupService.pageEpisodeByDateAndFormStatus(page,params);
        page.setRecords((List<CdcEpisodeDto>) new EmptyWarpper(result).warp());
        return R.packForBT(page);
    }

    /**
     * 跳转到主动入组
     */
    @RequestMapping("/in_group/{cdcEpisodeId}")
    public String inGroup(@PathVariable Long cdcEpisodeId, Model model) {
        JSONObject qcentity = sdsQcentityService.getQcentity();
        model.addAttribute("qcentity",qcentity);
        model.addAttribute("cdcEpisodeId",cdcEpisodeId);

        return PREFIX + "sdsmedicalgroup_in.html";
    }

    /**
     * 修改数据源定义
     */
    @RequestMapping(value = "/add")
    @ResponseBody
    public Object add(@RequestParam Map<String, Object> params) {

        String execUser = "手动入组";
        if (ShiroKit.getUser()!=null) {
            User user = ShiroKit.getUser();
            execUser = user.getLoginName();
        }
        SdsQcincaseEntity sdsQcincaseEntity = new SdsQcincaseEntity();
        sdsQcincaseEntity.setEpisodeId(Long.valueOf(params.get("episodeId").toString()));
        sdsQcincaseEntity.setEntityId(Long.valueOf(params.get("entityId").toString()));
        sdsQcincaseEntity.setInDate(new Date());
        sdsQcincaseEntity.setInTime(new Date());
        sdsQcincaseEntity.setState("I");
        sdsQcincaseEntity.setGroupStatus("ActivePart");
        sdsQcincaseEntity.setFillingStatus("NotFilled");
        sdsQcincaseEntity.setReportStatus("NotUp");
        boolean insert = false;
        if ("I".equals(sdsQcincaseEntity.getState())) {
            Wrapper<SdsQcincaseEntity> wrapper = new EntityWrapper<>();
            wrapper.eq("episode_id", sdsQcincaseEntity.getEpisodeId())
                    .eq("entity_id", sdsQcincaseEntity.getEntityId())
                    .eq("state", sdsQcincaseEntity.getState())
                    .eq("group_status", sdsQcincaseEntity.getGroupStatus())
                    .eq("filling_status", sdsQcincaseEntity.getFillingStatus())
                    .eq("report_status", sdsQcincaseEntity.getReportStatus());
            SdsQcincaseEntity qcincaseEntity = sdsQcincaseService.selectOne(wrapper);
            if (qcincaseEntity == null) {
                insert = sdsQcincaseEntity.insert();
            }
        }
        if (insert){
            SdsQcincaseOperlogEntity sdsQcincaseOperlogEntity = new SdsQcincaseOperlogEntity();
            sdsQcincaseOperlogEntity.setInCaseId(sdsQcincaseEntity.getId());
            sdsQcincaseOperlogEntity.setOperState("I");
            sdsQcincaseOperlogEntity.setOperDate(new Date());
            if (CommonUtil.isNotEmpty(params.get("reason"))) {
                sdsQcincaseOperlogEntity.setOperReason(params.get("reason").toString());
            }
            if (CommonUtil.isNotEmpty(params.get("resume"))) {
                sdsQcincaseOperlogEntity.setOperResume(params.get("resume").toString());
            }
            sdsQcincaseOperlogEntity.setOperUser(execUser);
            sdsQcincaseOperlogEntity.insert();
            //执行自动取值
            sdsQcfitemExecresultService.execItemResult(sdsQcincaseEntity.getId());
            //表单填充率
            try {
                sdsQcFormShowService.getItemResult(sdsQcincaseEntity.getId());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return R.ok();
    }

    @RequestMapping(value = "/getReasonByEntityId")
    @ResponseBody
    public Object getReasonByEntityId(@RequestParam Long entityId){
        Map<String, Object> map2 = new HashMap<>();
        map2.put("entityId", entityId);
        map2.put("isActive", 1);
        map2.put("isOnly", 0);
        List<SdsQcentityRuleEntity> qcentityRuleEntities = sdsQcentityRuleService.list(map2);

        JSONArray array = new JSONArray();
        for (SdsQcentityRuleEntity sdsQcentityRuleEntity : qcentityRuleEntities) {
            JSONObject obj = new JSONObject();
            if (Objects.equals("1", sdsQcentityRuleEntity.getRuleType()) && Objects.equals(1, sdsQcentityRuleEntity.getIsActive())){
                //准入
                obj.put("value", sdsQcentityRuleEntity.getId().toString());
                obj.put("text", sdsQcentityRuleEntity.getRuleDesc());
                array.add(obj);
            }

        }
        return array.toJSONString();
    }

    /**
     * @Desc 生成excel文件
     * @param params
     * @return
     * @Author syj
     * @Date 2022年05月31日07:53:00
     */
    @RequestMapping(value = "/createExcel")
    @ResponseBody
    public Object createExcel(@RequestParam Map<String, Object> params) {
        // 查询登录用户关联科室
        List<String> deptIds = sdsCommonService.getDeptIdsBySysUser();
        params.put("userLinkDepts", deptIds);
        String fileName = this.sdsMedicalGroupService.createExcel(params);
        return R.ok(fileName);
    }

    /**
     * @Desc 下载生成的Excel文件  .+ 后面的解决小数点取值不全问题
     * @param fileName
     * @param resp
     * @throws IOException
     * @Author wujiafeng
     * @Date 2018年11月14日 上午11:26:34
     */
    @RequestMapping(value = "excelDown/{fileName:.+}")
    @ResponseBody
    public void excelDown(@PathVariable String fileName, HttpServletResponse resp) throws IOException{
        String filePath = sysPro.getSysHome()+"file_download/sds/medicalgroup/";
        String excelFile = filePath + fileName;
        File file = new File(excelFile);
        if(file.exists()){
            //将文件名设置为中文
            byte[] tmpb = fileName.getBytes("GBK");
            String fileNameCN = new String(tmpb, "8859_1");
            resp.setContentType("application/octet-stream");
            resp.setHeader("Content-Disposition","attachment;filename=" + fileNameCN);
            resp.setContentLength((int) file.length());
            //打开指定文件流
            BufferedInputStream fileInputStream = new BufferedInputStream(new FileInputStream(excelFile));
            //写出流信息
            byte[] bytes =new byte[1024];
            OutputStream os = resp.getOutputStream();
            BufferedOutputStream fosObject = new BufferedOutputStream(os);
            while (fileInputStream.read(bytes)!=-1) {
                fosObject.write(bytes);
            }
            fileInputStream.close();
            fosObject.close();
            os.flush();
            os.close();
        }
    }
}
